import django_filters
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend,FilterSet
from rest_framework import filters
from rest_framework.decorators import action

from shoop import serializers
from shoop import models



class Sou(FilterSet):
    name = django_filters.CharFilter(field_name='name', lookup_expr='contains')
    class Meta:
        model = models.Commodity
        fields = ['name']


class Com(viewsets.ModelViewSet):
    queryset = models.Commodity.objects.all()
    serializer_class = serializers. CategorySerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = Sou



class Car(viewsets.ModelViewSet):
    queryset = models.Shopping_Cart.objects.all()
    serializer_class = serializers.Cart


    @action(detail=False, methods=['POST'])
    def addcar(self, request):
        nid = request.data.get('id')
        print(nid)
        mod = models.Shopping_Cart.objects.filter(commodity_id=nid)
        if mod:
            for i in mod:
                i.number += 1
                i.save()
                return Response({"msg": "数量已+1", "status": 200})
        else:
            models.Shopping_Cart.objects.create(commodity_id=nid, number=1)
            return Response({"msg": "添加成功", "status": 200})


